package hbec.kettle.etl.plugins.common;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import hbec.kettle.etl.common.constants.DataBase;
import hbec.kettle.etl.common.exception.ExceptionTracker;
import hbec.kettle.etl.common.util.DbcpUtils;

public class DBSource {
	private static final Logger logger = LoggerFactory.getLogger(DBSource.class);
	
	public static synchronized DataSource getDataSource(DataBase key) {
		DataSource source = DbcpUtils.dataSources.get(key);
		if (null == source) {
			throw new IllegalArgumentException(String.format(
					"Cannot get DataSource specified by key [%s] .", key));
		}
		return source;
	}
	
	public static synchronized Connection getConnection(DataBase key) {
		Connection c = null;
		DataSource dataSource = DbcpUtils.dataSources.get(key);
		try {
			c = dataSource.getConnection();
		} catch (SQLException e) {
			logger.error(ExceptionTracker.trace(e));
			throw new IllegalArgumentException(e.getCause());
		}
		if (null != c) {
			/*
			logger.info(String.format(
					"Key [%s] connect to database pool successfully .", key));*/
		} else {
			logger.error(String.format(
					"Key [%s]  connect to database pool failed .", key));
			throw new IllegalArgumentException(String.format(
					"Connection key [%s] error .", key));
		}
		return c;
	}
}
